﻿using System;
using System.Diagnostics;
using System.Web.Mvc;
using SnippetBox.Core.Infrastructure;

namespace SnippetBox.Core.Common.Mvc.Attributes {
    public class RequestTimingFilter : IActionFilter, IResultFilter {
        Stopwatch GetTimer(ControllerContext context, string name) {
            string key = "__timer__" + name;
            if (context.HttpContext.Items.Contains(key)) {
                return (Stopwatch)context.HttpContext.Items[key];
            }

            var result = new Stopwatch();
            context.HttpContext.Items[key] = result;
            return result;
        }

        public void OnActionExecuting(ActionExecutingContext filterContext) {
            GetTimer(filterContext, "action").Start();
        }

        public void OnActionExecuted(ActionExecutedContext filterContext) {
            GetTimer(filterContext, "action").Stop();
        }

        public void OnResultExecuting(ResultExecutingContext filterContext) {
            GetTimer(filterContext, "render").Start();
        }

        public void OnResultExecuted(ResultExecutedContext filterContext) {
            var renderTimer = GetTimer(filterContext, "render");
            renderTimer.Stop();

            var actionTimer = GetTimer(filterContext, "action");
            var response = filterContext.HttpContext.Response;

            if (response.ContentType == "text/html" && Settings.Current.Advanced.DebugMode) {
                response.Write(
                    String.Format(
                        "<p style=\"text-align: center;position: absolute;top: 0;width: 100%;\"><mark><b>Server</b>: Action '{1}/{0}Controller', Execute: {2}ms, Render: {3}ms.<span id=\"jsTimings\"/></mark></p><script>timings.init()</script>",
                        filterContext.RouteData.Values["controller"],
                        filterContext.RouteData.Values["action"],
                        actionTimer.ElapsedMilliseconds,
                        renderTimer.ElapsedMilliseconds
                        )
                    );
            }
        }
    }
}